package main

import (
	"fmt"
	"net"
	"strconv"
	"strings"
)

func isHttps(scheme string) bool {
	return strings.ToLower(scheme) == "https"
}

func findPort(scheme, port string) int {
	if port != "" {
		if p, e := strconv.Atoi(port); e == nil {
			return p
		}
	}
	if isHttps(scheme) {
		return 443
	}
	return 80
}

func parseAddr(addr, service string) (*net.TCPAddr, error) {
	hostname, port, _ := net.SplitHostPort(addr)
	ip := net.ParseIP(hostname)
	if ip != nil { // hostname 本身就是 IP 地址，则马上返回
		return &net.TCPAddr{IP: ip, Port: findPort(service, strings.TrimSpace(port))}, nil
	}
	// hostname 是个域名，则进行域名解析，取得 IP 地址
	addrs, err := net.LookupHost(hostname)
	if err != nil {
		return nil, err
	}
	if len(addrs) == 0 {
		return nil, fmt.Errorf("empty addrs for %s", hostname)
	}
	for _, ipaddr := range addrs {
		ip = net.ParseIP(ipaddr)
		if ip != nil {
			return &net.TCPAddr{IP: ip, Port: findPort(service, strings.TrimSpace(port))}, nil
		}
	}
	return nil, fmt.Errorf("no valid ip for %s, addrs: %v", hostname, addrs)
}
